<template>
    <div class="v-table">
        <div v-if="showAction" class="v-table-action">
            <div>
                <ASpace>
                    <slot name="buttons"></slot>
                </ASpace>
            </div>
            <div>
                <ASpace>
                    <slot name="buttonsExtra"></slot>
                </ASpace>
            </div>
        </div>
        <ATable
            class="tableRect"
            v-bind="$attrs"
            :columns="_columns"
            :data-source="dataTable"
            :row-key="rowKey"
            :loading="loading"
            :pagination="
                pagination && { ...pagination, pageSizeOptions, total }
            "
            :row-selection="rowSelection"
            @change="pagetionChange"
            v-on="$listeners"
        >
            <template
                v-for="columnSlot in columnSlotArr"
                #[columnSlot.key]="text, record, index"
            >
                <slot
                    v-if="!columnSlot.showEllipsis"
                    :name="columnSlot.key"
                    v-bind="{ row: record, $index: index, value: text }"
                    >{{ record[columnSlot.key] }}</slot
                >
                <slot
                    v-else
                    :name="columnSlot.key"
                    v-bind="{ row: record, $index: index, value: text }"
                >
                    <ATooltip v-bind="columnSlot.attrs">
                        <template slot="title">
                            {{ record[columnSlot.key] }}
                        </template>
                        <div
                            class="detail-content"
                            :style="{
                                width: columnSlot.attrs.width || '200px',
                            }"
                        >
                            {{ record[columnSlot.key] }}
                        </div>
                    </ATooltip>
                </slot>
            </template>
        </ATable>
    </div>
</template>
<script>
import { isArray } from "lodash-es";
import table from "./table";
export default {
    name: "VTable",
    mixins: [table],
    data() {
        return {
            dataTable: [],
            loading: false,
            columnSlotArr: [],
            paramsConfig: {
                page: 1,
                perPage: 10,
                pageSize: 10,
            },
            total: 0,
            // scroll
            scrollTimer: null, // 滚动定时器
            scrollDirection: "down", // 滚动方向 up向上 down向下
        };
    },
    computed: {
        _columns() {
            return [{ ...this.serialNumber }].concat(
                renderColumns(this.columns)
            );
        },
        rowSelection() {
            if (!(this.selection && isArray(this.selectedKeys))) return null;
            return {
                fixed: true,
                selectedRowKeys: this.selectedKeys,
                onChange: this.onSelectChange,
            };
        },
        serialNumber() {
            return renderSerialNumber(this.serial, this.paramsConfig);
        },
    },
    watch: {
        _columns: {
            handler() {
                this.columnSlotArr = setColunmsSlots(this._columns);
            },
            immediate: true,
        },
        params: {
            handler() {
                this.paramsConfig = {
                    ...this.paramsConfig,
                    ...this.params,
                };
            },
            immediate: true,
            deep: true,
        },
        paramsConfig: {
            handler() {
                if (this.isLazy) return;
                if (this.isReload) return;
                this.$nextTick(() => {
                    this.loadData();
                });
            },
            deep: true,
            immediate: true,
        },
        isReload: {
            handler(newVal) {
                if (newVal) this.loadData();
            },
            immediate: true,
        },
    },
    methods: {
        loadData() {
            this.loading = true;
            this.dataTable = [];
            if (this.http && typeof this.http === "function") {
                this.setTableData();
            } else {
                const data = this.data;
                if (isArray(data)) {
                    setTimeout(() => {
                        this.loading = false;
                        this.dataTable = data;
                        this.total = this.dataTotal || data.length || 0;
                    }, 500);
                }
            }
        },
        async setTableData() {
            // 不需要分页
            if (!this.pagination) {
                const res = await this.http(this.params);
                this.dataTable = res.data;
                this.total = res.data.length || 0;
                this.loading = false;
                this.$emit("update:is-reload", false);
                return;
            }
            try {
                const res = await this.http(this.paramsConfig);
                this.transformTable(res);
                this.loading = false;
                this.$emit("update:is-reload", false);
            } catch (error) {
                console.log(error);
            }
        },
        transformTable(res) {
            // 处理 php 或 java 不同格式
            const type = "php";
            if (type === "php") {
                const { data, meta } = res;
                this.dataTable = data;
                this.total = meta?.total;
            } else {
                // java
                console.log(res);
            }
        },
        onSelectChange(selectedRowKeys) {
            this.$emit("update:selectedKeys", selectedRowKeys);
        },
        pagetionChange({ current, pageSize }) {
            this.objAssest(current, pageSize);
            this.$emit("change", { current, pageSize });
        },
        objAssest(current, pageSize) {
            this.paramsConfig = {
                ...this.paramsConfig,
                ...this.params,
                pageSize,
                page: current,
            };
        },
        // 预留 -- > 表格滚动操作
        scrollFun() {
            // 如果定时器存在
            if (this.scrollTimer) {
                // 则先清除
                clearInterval(this.scrollTimer);
                this.scrollTimer = null;
            }
            console.log('111');

            this.scrollTimer = setInterval(() => {
                const scrollHeight = document.querySelectorAll(
                    `.tableRect .ant-table-body`
                )[0].scrollHeight;
                const clientHeight = document.querySelectorAll(
                    `.tableRect .ant-table-body`
                )[0].clientHeight;
                const scroll = scrollHeight - clientHeight;
                // 获取当前滚动条距离顶部高度		tableRect是a-table标签名
                const scrollTop = document.querySelectorAll(
                    `.tableRect .ant-table-body`
                )[0].scrollTop;
                console.log("scrollTop", scrollTop);
                // 向下滚动
                if (this.scrollDirection === "down") {
                    // 滚动速度
                    const temp = scrollTop + 10;
                    document.querySelectorAll(
                        `.tableRect .ant-table-body`
                    )[0].scrollTop = temp; // 滚动
                    // 距离顶部高度  大于等于 滚动长度
                    if (scroll <= temp) {
                        // 滚动到底部 停止定时器
                        clearInterval(this.scrollTimer);
                        this.scrollTimer = null;
                    }
                }
            }, 150);
        },
    },
};

function customNumber(config, index) {
    const number = (config.page - 1) * config.pageSize + (index + 1);
    return number < 10 ? "0" + number : number;
}

function renderColumns(columns) {
    return columns.map((item) => ({
        ...item,
        dataIndex: item.key,
        scopedSlots: item.scopedSlots || {
            customRender: item.dataIndex || item.key,
        },
    }));
}

function renderSerialNumber(serial, config) {
    return serial
        ? {
              title: "序号",
              width: "5%",
              dataIndex: "serialNumber",
              customRender: (text, record, index) =>
                  `${customNumber(config, index)}`,
          }
        : {};
}

function setColunmsSlots(_columns) {
    return _columns
        .filter((x) => x.scopedSlots)
        .map((i) => ({
            key: i.dataIndex || i.key,
            showEllipsis: i.showEllipsis,
            attrs: i.tooltipAttr || { placement: "top" },
        }));
}
</script>

<style scoped lang="less">
.v-table {
    &-action {
        margin-bottom: 15px;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    .detail-content {
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
    }

    /deep/ .ant-table {
        .ant-table-thead > tr > th,
        .ant-table-row > td {
            @media screen {
                @media (max-width: 768px) {
                    white-space: nowrap;
                }
                @media (max-width: 992px) {
                    word-break: keep-all;
                }
            }
        }
        .ant-table-thead > tr > th {
            background: #eff0f5;
            font-weight: bold;
        }
    }
}
</style>
